package com.zy.explore.common.infrastructure.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zy.explore.common.infrastructure.annotation.CheckToken;
import com.zy.explore.common.infrastructure.annotation.LoginToken;
import com.zy.explore.common.infrastructure.exception.BaseException;
import com.zy.explore.common.infrastructure.exception.MessageCode;
import com.zy.explore.common.infrastructure.util.JwtUtil;
import com.zy.explore.sys.application.service.SysUserService;
import com.zy.explore.sys.domain.mybatis.entity.SysUser;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 身份验证拦截器
 *
 * @author ChinaYin  主页:https://gitee.com/zy-explorej2ee 邮箱:zyexplorej2ee@sina.com
 * @date 2021年06月13日 15:08:35
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private SysUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = httpServletRequest.getHeader("Authorization");
            if (!StringUtils.isEmpty(token)) {
                // Bearer eyJhbGciOiJIUzI1NiJ9.eyJzd...
                token = token.substring(7);
            }
        }
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        // 检查是否有LoginToken注释，有则跳过认证
        if (method.isAnnotationPresent(LoginToken.class) && method.getAnnotation(LoginToken.class).required()) {
            return true;
        }
        // 检查是否有CheckToken注解，如果该注解值为false则跳过认证
        if (method.isAnnotationPresent(CheckToken.class) && !method.getAnnotation(CheckToken.class).required()) {
            return true;
        }

        // 执行认证
        if (token == null) {
            throw new BaseException(MessageCode.FORBIDDEN.getCode(), "无token，请重新登录");
        }
        // 获取 token 中的 user id
        String userId;
        try {
            DecodedJWT decode = JWT.decode(token);
            userId = decode.getClaim("id").asInt().toString();
        } catch (JWTDecodeException e) {
            throw MessageCode.TOKEN_ERROR.toException();
        }
        SysUser user = userService.getByPrimaryKey(Integer.parseInt(userId));
        if (user == null) {
            throw new BaseException(400, "用户不存在，请重新登录");
        }
        try {
            Boolean verify = JwtUtil.verifyToken(token, user);
            if (!verify) {
                throw new BaseException(MessageCode.UN_AUTHORIZATION.getCode(), "非法访问！");
            }
        } catch (ExpiredJwtException e) {
            throw new BaseException(MessageCode.UN_AUTHORIZATION.getCode(), "token已过期！");
        } catch (SignatureException e) {
            throw new BaseException(MessageCode.UN_AUTHORIZATION.getCode(), "不合法token！");
        }
        // 将认证通过的用户信息设置到SecurityContextHolder中备用
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
